package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.StudentMapper;
import com.itheima.pojo.Clazz;
import com.itheima.pojo.PageResult;
import com.itheima.pojo.Student;
import com.itheima.pojo.StudentQueryParam;
import com.itheima.service.ClazzService;
import com.itheima.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student> implements StudentService {
@Autowired
private ClazzService clazzService;
    @Override
    public PageResult<Student> getPage(StudentQueryParam studentQueryParam) {
        //设置条件
        //select * from student where name like(?)
        //select * from student where degree = ?
        //所属班级 用map集合把班级id与班级名称对应起来,遍历学员 给对应的学院分班级

        LambdaQueryWrapper<Student> lqw = new LambdaQueryWrapper<>();
        lqw.like(studentQueryParam.getName()!=null && studentQueryParam.getName().length()>0,Student::getName,studentQueryParam.getName());
        lqw.eq(studentQueryParam.getDegree()!=null,Student::getDegree,studentQueryParam.getDegree());
        lqw.eq(studentQueryParam.getClazzId()!=null,Student::getClazzId,studentQueryParam.getClazzId());

        List<Clazz> classList = clazzService.list();
        //将集合转换为Map
        Map<Integer, String> clazzMap = classList.stream().collect(Collectors.toMap(Clazz::getId, Clazz::getName));




        //分页查询
        Page<Student> studentPage = new Page<>(studentQueryParam.getPage(), studentQueryParam.getPageSize());
        Page<Student> page = this.page(studentPage,lqw);

        List<Student> students = page.getRecords();
        // //遍历学生
        for (Student student : students) {
        student.setClazzName(clazzMap.get(student.getClazzId()));
        }
        return new PageResult<Student>(page.getTotal(),page.getRecords());
    }

    @Override
    public void saveStu(Student student) {
        student.setUpdateTime(LocalDateTime.now());
        this.save(student);
    }
}
